<template>
  <div class="app-container">
    <!-- 打印 -->
    <div class="printContent2">
      <div style="width: 100%; height: 650px; page-break-after: always" v-for="(item, index) in pages">
        <div class="center size-24 title">福建荣信鞋业有限公司</div>
        <div class="center size-24 title">
          (收款单) <span style="position: absolute; right: 50px; font-size: 14px">第{{ index + 1 }} 页 共 {{ totalPages }} 页</span>
        </div>
        <div class="header" style="display: flex; justify-content: space-evenly">
          <span>收款单号：{{ printObj.receiptNo }}</span>
          <span>实收日期：{{ printObj.recDate }}</span>
          <span>打印日期：{{ currentTime }}</span>
        </div>
        <div class="mainTable">
          <table style="text-align: center; font-size: 16px; margin-top: 10px">
            <tr>
              <td class="size-16 center">客人发票号</td>
              <td class="size-16 center">出货日期</td>
              <td class="size-16 center">船期</td>
              <td class="size-16 center">品牌</td>
              <td class="size-16 center">收款类型</td>
              <td class="size-16 center">币种</td>
              <td class="size-16 center">实收金额</td>
            </tr>
            <tr v-for="item2 in item">
              <td class="size-16 center">{{ item2.custInvNo }}</td>
              <td class="size-16 center">{{ item2.outDate }}</td>
              <td class="size-16 center">{{ item2.shipDate }}</td>
              <td class="size-16 center">{{ item2.custom }}</td>
              <td class="size-16 center">{{ item2.arType }}</td>
              <td class="size-16 center">{{ item2.currency }}</td>
              <td class="size-16 center">{{ item2.recAmt }}</td>
            </tr>
            <tr v-if="isLastPage(index, totalPages)">
              <td colspan="4" class="size-16 left">单据笔数合计：{{ printObj.tatalNum }}</td>
              <td colspan="2" class="size-16 left">实收合计：</td>
              <td colspan="2" class="size-16 left">{{ printObj.totalAmt }}</td>
            </tr>
            <tr v-if="isLastPage(index, totalPages)">
              <td colspan="7" class="size-16 left">备注：{{ printObj.totalRemark }}</td>
            </tr>
          </table>
        </div>
        <div class="mainTable footer" style="margin-top: 30px" v-if="isLastPage(index, totalPages)">
          <span style="margin-left: 100px">复审：</span>
          <span style="margin-left: 100px">审核：</span>
          <span style="margin-left: 100px">制单：{{ currentUser }}</span>
        </div>
      </div>
    </div>

    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <div class="mt10" style="width: 100%; background-color: white">
      <el-card shadow="never" :body-style="{ padding: '5px 10px 0px' }">
        <div class="flex AIC">
          <h1 class="f16">费用查询明细</h1>
          <el-button class="ml10" type="primary" size="default" @click="btnClick">实收操作</el-button>
        </div>
        <Table
          :tableHeader="tableHeader"
          :tableData="tableData"
          selection
          class="mt10"
          :isLoading="isLoading"
          @currentRow="currentRow"
          :summaryData="summaryData"
          summary
          @selectList="selectTableList"
          @sortChange="sortChange"
          @currentRow1="dbClick"
        />
      </el-card>
      <el-card shadow="never" :body-style="{ padding: '0px' }">
        <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
      </el-card>
    </div>

    <el-drawer v-model="drawer" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <div class="flex AIC" style="flex-direction: column">
        <div class="flex mt10 JCC" style="width: 100%; background-color: white">
          <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
            <div class="flex">
              <h1 class="f16">实收操作</h1>
            </div>
            <Find :OriginalFilter="{ static: true }" :formList="formList4" @findClicked="findClicked4" />
            <Table
              @download="download3"
              :tableHeader="tableHeader3"
              :tableData="tableData3"
              :summaryData="summaryData3"
              @inputChange="inputChange3"
              summary
              selection
              class="mt10"
              @selectList="selectTableList3 as any"
            />
          </el-card>

          <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
            <div class="flex">
              <h1 class="f16">实收操作</h1>
            </div>
            <Find :OriginalFilter="{ static: true }" :formList="formList3" @findClicked="findClicked3" />
            <Table
              @confirmChange="confirmChange2"
              @download="download2"
              :tableHeader="tableHeader2"
              :tableData="tableData2"
              selection
              class="mt10"
              @selectList="selectTableList2"
              @currentRow="currentRow2"
            />
            <el-card shadow="never" :body-style="{ padding: '0px' }">
              <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
            </el-card>
          </el-card>
        </div>
      </div>
    </el-drawer>

    <el-drawer v-model="drawer2" :direction="'ttb'" size="small" :with-header="false">
      <span @click="drawer2 = false" style="float: right; cursor: pointer; color: rgb(7, 7, 7)">X</span>
      <div class="flex AIC" style="flex-direction: column">
        <div class="flex mt10 JCC" style="width: 100%; background-color: white">
          <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }">
            <div class="flex">
              <h1 class="f16">出货明细</h1>
            </div>
            <Table :tableHeader="tableHeader9" :tableData="tableData9" class="mt10" />
            <el-card shadow="never" :body-style="{ padding: '0px' }">
              <PageModule :PageData="{ total: total2, buttonS: true }" @pageSizeChange="handleSizeChange2" @pageChange="handleCurrentChange2" />
            </el-card>
          </el-card>
        </div>
      </div>
    </el-drawer>
  </div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import LoginWork from '@/utils/LoginWork'
import router from '@/router'
import { formateData } from '@/plugins/mixinJ'
import fileRequest from '@/utils/fileRequest'
import JMessage from '@/utils/JMessage'
export default defineComponent({
  name: 'FinancialReceivableOperations'
})
</script>
<script lang="ts" setup>
import { i18n, Jzhcn } from '@/i18n'
import { computed, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'
import { debounce, forEach } from 'lodash'
import { onMounted, watch } from 'vue'
const drawer = ref(false)
const drawer2 = ref(false)
const currentTime = computed(() => {
  const now = new Date()
  const year = now.getFullYear()
  const month = now.getMonth() + 1 // 月份从0开始，需要加1
  const day = now.getDate()
  return `${year}-${month}-${day}`
})

const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '收款单号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '客人发票号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '报关发票号',
    inputValue: ''
  },
  {
    type: 'input',
    inputPlaceholder: '信用证号',
    inputValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '交单日期',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '出货日期开始',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '出货日期结束',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '船期开始',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '船期结束',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'select',
    selectP: '品牌',
    selectValue: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectLabel: '收款类型',
    selectValue: '全部',
    selectP: '收款类型',
    selectOptions: [
      {
        optionLabel: '全部',
        optionValue: '全部'
      },
      {
        optionLabel: 'LC',
        optionValue: 'LC'
      },
      {
        optionLabel: 'TT',
        optionValue: 'TT'
      }
    ]
  },
  {
    type: 'select',
    selectValue: '全部',
    selectP: '检核状态',
    selectLabel: '检核状态',
    selectOptions: [
      {
        optionLabel: '全部',
        optionValue: '全部'
      },
      {
        optionLabel: '未检核',
        optionValue: '未检核'
      },
      {
        optionLabel: '已检核',
        optionValue: '已检核'
      }
    ]
  },
  {
    type: 'input',
    inputPlaceholder: '操作人',
    inputValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '实收日期开始',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'dateSingle',
    placeholder: '实收日期结束',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'select',
    selectValue: '全部',
    selectP: '未收金额',
    selectLabel: '未收金额',
    selectOptions: [
      {
        optionLabel: '全部',
        optionValue: '全部'
      },
      {
        optionLabel: '等于0',
        optionValue: '等于0'
      },
      {
        optionLabel: '大于0',
        optionValue: '大于0'
      }
    ]
  },
  {
    type: 'select',
    selectValue: '全部',
    selectP: '类型',
    selectLabel: '类型',
    selectOptions: [
      {
        optionLabel: '全部',
        optionValue: '全部'
      },
      {
        optionLabel: '大货',
        optionValue: '大货'
      },
      {
        optionLabel: '样品',
        optionValue: '样品'
      },
      {
        optionLabel: '其他',
        optionValue: '其他'
      }
    ]
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  }
]) as any
const formList2 = ref([
  {
    type: 'button',
    checkboxLabel: '实收操作',
    bgColor: '#ED5565'
  }
])
const formList3 = ref([
  {
    type: 'button',
    checkboxLabel: '当前行检核'
  },
  {
    type: 'button',
    checkboxLabel: '当前行取消检核'
  }
])
const formList4 = ref([
  {
    type: 'dateSingle',
    placeholder: '实收日期',
    dateLabel: '',
    dateValue: ''
  },
  {
    type: 'button',
    checkboxLabel: '实收填充',
    bgColor: '#ED5565'
  }
])

const tableHeader = ref([
  {
    change: true,
    width: '90',
    label: '应收金额',
    prop: 'arAmt'
  },
  {
    change: true,
    label: '未收金额',
    prop: 'actAmt'
  },
  {
    label: '累计实收',
    prop: 'recAmt'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    label: '船务备注',
    prop: 'shipRemark'
  },
  {
    change: true,
    label: '类型',
    prop: 'orderType'
  },
  {
    change: true,
    label: '报关发票号',
    prop: 'customsInvNo'
  },
  {
    change: true,
    label: '客人发票号',
    prop: 'custInvNo'
  },
  {
    change: true,
    label: '品牌',
    prop: 'custom'
  },
  {
    change: true,
    label: '出货日期',
    prop: 'outDate'
  },
  {
    change: true,
    width: 120,
    label: '船期',
    prop: 'shipDate'
  },
  {
    change: true,
    label: '出货数量',
    prop: 'outPair'
  },
  {
    change: true,
    label: '币种',
    prop: 'currency'
  },
  {
    change: true,
    label: '添加港口单价',
    prop: 'premium'
  },
  {
    change: true,
    label: '出货金额',
    prop: 'outAmt'
  },
  {
    change: true,
    label: '附加费用',
    prop: 'additionalCost'
  },
  {
    change: true,
    label: '起运港-目的港',
    prop: 'destPort'
  },
  {
    change: true,
    label: '出口类型',
    prop: 'exportType'
  },
  {
    change: true,
    label: '收款类型',
    prop: 'arType'
  },
  {
    change: true,
    width: 120,
    label: '信用证号',
    prop: 'creditNo'
  },
  {
    change: true,
    label: '交单日期',
    prop: 'deliveryDate'
  },
  {
    change: true,
    type: 'svg',
    label: '检核状态',
    prop: 'cfmFlag'
  },
  {
    change: true,
    label: '检核时间',
    prop: 'cfmTime'
  }
])
// 表一模块
// 表一按钮
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
    formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '检核状态').selectValue =
      '全部'
    formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '收款类型').selectValue =
      '全部'
    formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '未收金额').selectValue =
      '全部'
    formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '类型').selectValue =
      '全部'
  }
  if (content === '导出') {
    const res = (await fileRequest.post(`/pc/pay/export`, {
      actAmt:
        formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '未收金额')
          ?.selectValue === '全部'
          ? '2'
          : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '未收金额')
              ?.selectValue === '大于0'
          ? '1'
          : '0',
      additionalCost: '',
      arAmt: '',
      arDate: '',
      arType:
        formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '收款类型')
          ?.selectValue === '全部'
          ? ''
          : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '收款类型')
              ?.selectValue,
      beginTime: formList.value.find((item: any) => item.placeholder === '实收日期开始')?.dateValue,
      cfmFlag:
        formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '检核状态')
          ?.selectValue === '全部'
          ? ''
          : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '检核状态')
              ?.selectValue === '已检核'
          ? 'Y'
          : 'N',
      cfmTime: '',
      cfmUser: '',
      companyId: '',
      creditNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '信用证号'
      )?.inputValue,
      currency: '',
      custInvNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '客人发票号'
      )?.inputValue,
      custom: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
        ?.selectValue,
      customsInvNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '报关发票号'
      )?.inputValue,
      deliveryDate: formList.value.find((item: any) => item.placeholder === '交单日期')?.dateValue,
      deliveryTime: '',
      destPort: '',
      discountAmt: '',
      endTime: formList.value.find((item: any) => item.placeholder === '实收日期结束')?.dateValue,
      exportType: '',
      invoiceNo: '',
      orderType:
        formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '类型')
          ?.selectValue === '全部'
          ? ''
          : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '类型')
              ?.selectValue,
      outAmt: '',
      outDate: '',
      outPair: '',
      outTime: '',
      payDays: '',
      premium: '',
      recAmt: '',
      recDate: '',
      recTime: '',
      receiptNo: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '收款单号'
      )?.inputValue,
      remark: '',
      rowid: '',
      shipDBeginTime: formList.value.find((item: any) => item.placeholder === '船期开始')?.dateValue,
      shipDEndTime: formList.value.find((item: any) => item.placeholder === '船期结束')?.dateValue,
      shipDate: '',
      shipTime: '',
      smBeginTime: formList.value.find((item: any) => item.placeholder === '出货日期开始')?.dateValue,
      smEndTime: formList.value.find((item: any) => item.placeholder === '出货日期结束')?.dateValue,
      sysDate: '',
      sysUser: formList.value.find(
        (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '操作人'
      )?.inputValue,
      pageNum: currentPage.value,
      pageSize: pageSize.value
    })) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}
const tableData = ref([])
const isLoading = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}
const summaryData = ref<summaryDataType[]>([
  {
    index: 1,
    num: 0
  },
  {
    index: 2,
    num: 0
  },
  {
    index: 3,
    num: 0
  },
  {
    index: 11,
    num: 0
  },
  {
    index: 14,
    num: 0
  },
  {
    index: 15,
    num: 0
  }
])
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
const flag = ref(1)
const clickNumber = (val: any) => {
  flag.value = val
  getTableList()
}
const sortChange = (order: any, prop: any, column: any) => {
  let orderFlag = null
  if (order === null) {
    orderFlag = null
  } else if (order === 'ascending') {
    orderFlag = 1
  } else if (order === 'descending') {
    orderFlag = 2
  }
  getTableList(orderFlag, prop)
}
// 获取表数据
const getTableList = debounce(async (orderFlag: any = '', orderName: string = '') => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/pc/pay/receivable/list', {
    actAmt:
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '未收金额')
        ?.selectValue === '全部'
        ? '2'
        : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '未收金额')
            ?.selectValue === '大于0'
        ? '1'
        : '0',
    additionalCost: '',
    arAmt: '',
    arDate: '',
    arType:
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '收款类型')
        ?.selectValue === '全部'
        ? ''
        : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '收款类型')
            ?.selectValue,
    beginTime: formList.value.find((item: any) => item.placeholder === '实收日期开始')?.dateValue,
    cfmFlag:
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '检核状态')
        ?.selectValue === '全部'
        ? ''
        : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '检核状态')
            ?.selectValue === '已检核'
        ? 'Y'
        : 'N',
    cfmTime: '',
    cfmUser: '',
    companyId: '',
    creditNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '信用证号'
    )?.inputValue,
    currency: '',
    custInvNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '客人发票号'
    )?.inputValue,
    custom: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      ?.selectValue,
    customsInvNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '报关发票号'
    )?.inputValue,
    deliveryDate: formList.value.find((item: any) => item.placeholder === '交单日期')?.dateValue,
    deliveryTime: '',
    destPort: '',
    discountAmt: '',
    endTime: formList.value.find((item: any) => item.placeholder === '实收日期结束')?.dateValue,
    exportType: '',
    invoiceNo: '',
    orderType:
      formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '类型')
        ?.selectValue === '全部'
        ? ''
        : formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '类型')
            ?.selectValue,
    outAmt: '',
    outDate: '',
    outPair: '',
    outTime: '',
    payDays: '',
    premium: '',
    recAmt: '',
    recDate: '',
    recTime: '',
    receiptNo: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '收款单号'
    )?.inputValue,
    remark: '',
    rowid: '',
    shipDBeginTime: formList.value.find((item: any) => item.placeholder === '船期开始')?.dateValue,
    shipDEndTime: formList.value.find((item: any) => item.placeholder === '船期结束')?.dateValue,
    shipDate: '',
    shipTime: '',
    smBeginTime: formList.value.find((item: any) => item.placeholder === '出货日期开始')?.dateValue,
    smEndTime: formList.value.find((item: any) => item.placeholder === '出货日期结束')?.dateValue,
    sysDate: '',
    sysUser: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '操作人'
    )?.inputValue,

    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  tableData.value = tableDataList.list.map((item: any) => {
    return item
  })
  total.value = tableDataList.total
  currentRow()
  summaryData.value[0].num = tableDataList.result.arAmt // 应收金额
  summaryData.value[1].num = tableDataList.result.actAmt // 未收金额
  summaryData.value[2].num = tableDataList.result.recAmt //累计实收
  summaryData.value[3].num = tableDataList.result.outPair // 出货数量
  summaryData.value[4].num = tableDataList.result.outAmt // 出货金额
  summaryData.value[5].num = tableDataList.result.additionalCost // 附加费用
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
watch(drawer, (newVal: any) => {
  if (newVal === false) {
    getTableList()
  }
})

// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
}

let localArr = JSON.parse(localStorage.getItem('selectedList') as any) || ([] as any)
const selectedLists = ref([]) as any
const selectTableList = (selectedList: any, ref: any) => {
  if (selectedList.some((item: any) => item.cfmFlag !== 'Y')) {
    JMessage.error('船务未检核的记录不能进行操作')
    getTableList()
    return
  }
  selectedLists.value = selectedList
  if (selectedList.length > 0) {
    selectedList.forEach((item: any) => {
      localArr.push(item)
    })
    localStorage.setItem('selectedList', JSON.stringify([...new Set(localArr)]))
  }
}
const dbClick = () => {
  drawer2.value = true
  getTableList9()
}

// 出货明细
const tableHeader9 = ref([
  {
    label: '客人PI',
    prop: 'customPiNo'
  },
  {
    label: '工厂',
    prop: 'factory'
  },
  {
    label: '工厂指令',
    prop: 'factoryLotNo'
  },
  {
    label: '订单数量',
    prop: 'orderQty'
  },
  {
    width: 110,
    label: '柜号',
    prop: 'containerNo'
  },
  {
    label: '出货数量',
    prop: 'outQty'
  },
  {
    label: '单价',
    prop: 'custPrice'
  },
  {
    label: '币种',
    prop: 'custCur'
  },
  {
    label: '金额',
    prop: 'amount'
  },
  {
    label: '型体',
    prop: 'styleNo'
  },
  {
    label: '颜色',
    prop: 'colorName'
  },
  {
    label: '颜色代号',
    prop: 'colorCode'
  },
  {
    label: '品牌',
    prop: 'brand'
  },
  {
    width: 110,
    label: '鞋名',
    prop: 'styleName'
  },
  {
    label: '客户型体',
    prop: 'custStyle'
  },
  {
    label: '季度',
    prop: 'season'
  },
  {
    label: '交单日期',
    prop: 'deliveryDate'
  }
])
const tableData9 = ref([])

// 表二模块
const deptOptions = ref([]) as any
const categoryOptions = ref([]) as any
const settleMethodOptions = ref([]) as any
const tableHeader2 = ref([
  {
    width: 120,
    type: 'functionRow'
  },
  {
    width: '150',
    label: '备注',
    prop: 'remark'
  },
  {
    change: true,
    width: '150',
    label: '收款单号',
    prop: 'receiptNo'
  },
  {
    change: true,
    label: '实收日期',
    prop: 'recDate'
  },
  {
    change: true,
    width: '80',
    label: '实收金额',
    prop: 'recAmt'
  },
  {
    change: true,
    width: '50',
    label: '操作员',
    prop: 'sysUser'
  },
  {
    width: 120,
    change: true,
    label: '操作时间',
    prop: 'sysDate'
  },
  {
    change: true,
    label: '检核',
    prop: 'cfmFlag'
  }
])
const tableData2 = ref([]) as any
// 表二按钮
const btnClick = () => {
  drawer.value = true
  getTableList2()
  getTableList3()
}
const getTableList2 = async () => {
  const res = (await service.post(`/pc/pay/detail/list`, currentTableRow.value)) as any
  tableData2.value = res.map((item: any) => {
    if (item.cfmFlag === 'Y') {
      item.functionRow = [
        {
          label: '打印',
          bgColor: '#1C84C6'
        }
      ]
    } else {
      item.functionRow = [
        {
          label: '删除',
          bgColor: 'red'
        }
      ]
    }
    item.change = 'Y'
    return item
  })
  currentRow2()
}
const download2 = async (row: any, item2: any) => {
  console.log(row, item2)
  if (item2.label === '删除') {
    const res = (await LoginWork.post('/pc/pay/deleteDetail', currentTableRow2.value)) as any
    if (res.code === 200) {
      JMessage.success('删除成功')
      getTableList2()
    } else {
      JMessage.error(res.message)
    }
  } else if (item2.label === '打印') {
    printSummary()
  }
}
const findClicked3 = async (content: string) => {
  if (content === '当前行检核') {
    if (currentTableRow2.value.receiptNo === null) {
      JMessage.error('收款单号不能为空')
      return
    }
    const res2 = (await LoginWork.post(`/pc/pay/cfm?receiptNo=${currentTableRow2.value.receiptNo}&cfmFlag=${'Y'}`)) as any
    if (res2.code === 200) {
      JMessage.success('当前行检核成功')
      getTableList2()
    } else {
      JMessage.error(res2.message)
    }
  }
  if (content === '当前行取消检核') {
    if (currentTableRow2.value.receiptNo === null) {
      JMessage.error('收款单号不能为空')
      return
    }
    const res2 = (await LoginWork.post(`/pc/pay/cfm?receiptNo=${currentTableRow2.value.receiptNo}&cfmFlag=${''}`)) as any
    if (res2.code === 200) {
      JMessage.success('当前行取消检核成功')
      getTableList2()
    } else {
      JMessage.error(res2.message)
    }
  }
}
const isLoading9 = ref(true)
// 总计
interface summaryDataType {
  index: number
  num: number | undefined
}

// 分页器
const currentPage2 = ref(1)
const pageSize2 = ref(40)
const total2 = ref(0)
const handleSizeChange2 = (val: number) => {
  pageSize2.value = val
  getTableList9()
}
const handleCurrentChange2 = (val: number) => {
  currentPage2.value = val
  getTableList9()
}
const currentTableRow2 = ref({}) as any
const currentRow2 = async (row: any = tableData2.value[0] ? tableData2.value[0] : {}) => {
  currentTableRow2.value = row
}
const selectedLists2 = ref([]) as any
const selectTableList2 = (selectedList: any) => {
  selectedLists2.value = selectedList
}
const selectedLists3 = ref([]) as any
const selectTableList3 = (selectedList: any) => {
  selectedLists3.value = selectedList
}
// 获取表数据
const getTableList9 = debounce(async () => {
  isLoading9.value = true
  let tableDataList = await service.post<any, any>('/pc/pay/infoList', {
    invoiceNo: currentTableRow.value.invoiceNo,
    companyId: currentTableRow.value.companyId,
    pageNum: currentPage2.value,
    pageSize: pageSize2.value
  })
  isLoading9.value = false
  console.log(tableDataList)

  tableData9.value = tableDataList
  // currentRow2()
}, 500)
onMounted(() => {
  getTableList9()
})
// 点击表给另一张表传数据
// const currentTableRow2 = ref({}) as any
// const currentRow2 = async (row: any = tableData2.value[0]) => {
//   currentTableRow2.value = row
// }
const selectList = async () => {
  const res2 = (await service.get('/back/getPcCostType')) as any
  res2.forEach((item: any, index: any) => {
    // if (item === null && !item.type_name && !item.TYPE_NO) return
    categoryOptions.value.push({
      value: `${item.typeName}`,
      label: `${item.typeName}`
    })
    formList.value
      .find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '费用类型')
      ?.selectOptions?.push({
        optionKey: `${item.typeName}`,
        optionLabel: `${item.typeName}`,
        optionValue: `${item.typeName}`
      })
  })
  deptOptions.value.push(
    {
      value: `荣阳车间`,
      label: `荣阳车间`
    },
    {
      value: `荣信研发`,
      label: `荣信研发`
    }
  )
  settleMethodOptions.value.push(
    {
      value: `荣阳大货`,
      label: `荣阳大货`
    },
    {
      value: `荣信`,
      label: `荣信`
    }
  )
  formList.value
    .find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '结算方式')
    ?.selectOptions?.push(
      {
        optionKey: `荣阳大货`,
        optionLabel: `荣阳大货`,
        optionValue: `荣阳大货`
      },
      {
        optionKey: `荣信`,
        optionLabel: `荣信`,
        optionValue: `荣信`
      }
    )
  formList.value
    .find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '部门')
    ?.selectOptions?.push(
      {
        optionKey: `荣阳车间`,
        optionLabel: `荣阳车间`,
        optionValue: `荣阳车间`
      },
      {
        optionKey: `荣信研发`,
        optionLabel: `荣信研发`,
        optionValue: `荣信研发`
      }
    )
}
onMounted(() => {
  selectList()
})

const confirmChange2 = async (row: any) => {
  // 修改备注调用接口
  if (row.remark !== null) {
    if (row.receiptNo === null) {
      JMessage.error('收款单号不能为空')
      getTableList()
      return
    }
    const res = (await LoginWork.post(`/pc/pay/updateRemark?receiptNo=${row.receiptNo}&remark=${encodeURIComponent(row.remark)}`)) as any
    if (res.code === 200) {
      JMessage.success('修改成功')
    } else {
      JMessage.error(res.message)
      getTableList()
    }
  }
}

const tableData3 = ref([])
const tableHeader3 = ref([
  {
    width: 80,
    type: 'functionRow'
  },
  {
    width: 110,
    change: true,
    label: '报关发票号',
    prop: 'customsInvNo'
  },
  {
    width: 110,
    change: true,
    label: '客人发票号',
    prop: 'custInvNo'
  },
  {
    change: true,
    label: '收款类型',
    prop: 'arType'
  },
  {
    change: true,
    width: '90',
    label: '应收金额',
    prop: 'arAmt'
  },
  {
    change: true,
    label: '未收金额',
    prop: 'actAmt'
  },
  {
    label: '累计实收',
    prop: 'recAmt'
  },
  {
    label: '备注',
    prop: 'remark'
  },
  {
    change: true,
    label: '出货数量',
    prop: 'outPair'
  },
  {
    change: true,
    label: '出货金额',
    prop: 'outAmt'
  },
  {
    change: true,
    label: '出口类型',
    prop: 'exportType'
  }
])
const download3 = async (row: never, item2: any) => {
  if (item2.label === '删除') {
    tableData3.value.splice(tableData3.value.indexOf(row), 1)
    localStorage.setItem('selectedList', JSON.stringify(tableData3.value)) as any
    localArr = tableData3.value
  }
}
const findClicked4 = async (content: string) => {
  if (content === '实收填充') {
    if (selectedLists3.value.length === 0) {
      JMessage.warning('请勾选数据')
      return
    }
    const date = formList4.value.find((item: any) => item.placeholder === '实收日期')?.dateValue
    if (!date) {
      JMessage.warning('请输入实收日期')
      return
    }
    selectedLists3.value.forEach((item: any) => {
      item.recDate = date
      item.recAmt = item.recAmt ? item.recAmt : item.actAmt
    })
    const res = (await LoginWork.post(`/pc/pay/addDetail`, selectedLists3.value)) as any
    if (res.code === 200) {
      JMessage.success('结算成功')
      localStorage.setItem('selectedList', JSON.stringify([]))
      getTableList()
      getTableList2()
      getTableList3()
    } else {
      JMessage.error(res.message)
    }
  }
}

const summaryData3 = ref<summaryDataType[]>([
  {
    index: 5,
    num: 0
  },
  {
    index: 6,
    num: 0
  },
  {
    index: 7,
    num: 0
  },
  {
    index: 9,
    num: 0
  },
  {
    index: 10,
    num: 0
  }
])
const getTableList3 = async () => {
  const res = JSON.parse(localStorage.getItem('selectedList') as any)
  tableData3.value = res.map((item: any) => {
    if (item.actAmt !== 0) {
      item.change = 'Y'
      item.disableConfirm = true
    }
    item.functionRow = [
      {
        label: '删除',
        bgColor: 'red'
      }
    ]
    item.change = 'Y'
    item.recAmt = ''
    return item
  })
  summaryData3.value[0].num = tableData3.value.reduce((prev: any, curr: any) => prev + curr.arAmt, 0).toFixed(2)
  summaryData3.value[1].num = tableData3.value.reduce((prev: any, curr: any) => prev + curr.actAmt, 0).toFixed(2)
  summaryData3.value[2].num = tableData3.value.reduce((prev: any, curr: any) => prev + curr.recAmt, 0)
  summaryData3.value[3].num = tableData3.value.reduce((prev: any, curr: any) => prev + curr.outPair, 0)
  summaryData3.value[4].num = tableData3.value.reduce((prev: any, curr: any) => prev + curr.outAmt, 0).toFixed(2)

  currentRow2()
}
const inputChange3 = async (row: any, currentLabel: any) => {
  summaryData3.value[2].num = tableData3.value.reduce((prev: any, curr: any) => prev + Number(curr.recAmt), 0).toFixed(2)
}

// 打印
const currentUser = ref('') as any
const printObj = ref({}) as any
const splitNum = 32
// 计算总页数
const totalPages = computed(() => Math.ceil(printObj.value.detailList.length / splitNum))
// 分割数据为多页
const pages = computed(() => {
  const result = []
  if (printObj.value.detailList && printObj.value.detailList.length !== 0) {
    for (let i = 0; i < printObj.value.detailList.length; i += splitNum) {
      result.push(printObj.value.detailList.slice(i, i + splitNum))
    }
  }
  return result
})
const isLastPage = (pageIndex: number, totalPages: number) => {
  return pageIndex === totalPages - 1
}

const printSummary = async () => {
  const res = (await LoginWork.post(`/pc/pay/print`, currentTableRow2.value)) as any
  const userInfo = JSON.parse(sessionStorage.getItem('userInfo') || '') as any
  currentUser.value = userInfo.chiName
  printObj.value = res.data
  setTimeout(() => {
    const qrCodeContainer = document.querySelector<any>('.printContent2')
    if (qrCodeContainer) {
      qrCodeContainer.style.display = 'block'
      const printWindow = window.open('', '_blank')
      printWindow!.document.write(`
      <!DOCTYPE html>
      <html>
        <head>
          <title>&nbsp;</title>
          <link rel="stylesheet" type="text/css" href="print.css" media="print">
          <style>
            body, html {
              margin: 0;
              padding: 0;
            }
            @page {
              size: auto;
            }
            @media print {
                /* 打印时的样式 */

                /* 其他打印样式 */
            }
            h2 {
                    margin-left: initial; /* 或者设置适合打印的左边距 */
                    page-break-inside: avoid; /* 避免在h2元素内部分页 */
                }
            .headerTable {
                height: auto;
                border: 0px solid #000;
                text-align: center;
                display: flex;
                margin: 20px 20px 0px;
                vertical-align: top;
            }

            .title {
                display: flex;
                justify-content: center;
                margin-bottom: 10px;
            }

            .center {
                text-align: center;
            }

            .right {
                text-align: right;
            }

            .left {
                text-align: left;
            }

            .no-padding {
                padding: 0;
            }

            .no-margin {
                margin: 0;
            }

            .margin-5 {
                margin: 5px;
            }

            .margin-top-5 {
                margin-top: 5px;
            }

            .margin-top-15 {
                margin-top: 15px;
            }

            .size-8 {
                font-size: 8px !important;
            }

            .size-10 {
                font-size: 10px;
            }

            .size-12 {
                font-size: 12px;
            }

            .size-14 {
                font-size: 14px;
            }

            .size-16 {
                font-size: 17px;
            }

            .size-18 {
                font-size: 18px;
            }

            .size-24 {
                font-size: 24px;
            }

            #date-tip {
                position: relative;
            }

            span.tip {
                display: inline-block;
                height: 14px;
                line-height: 14px;
                margin-right: 30px;
            }

            table {
                font-size: 10px;
                border-collapse: collapse;
                border-spacing: 0;
                border-collapse: collapse;
                border-spacing: 0;
                empty-cells: show;
                width: 100%;
            }

            table th,
            table td {
                border: 1px solid #000;
                font-size: 12px;
            }

            table.no-border,
            table.no-border th,
            table.no-border td {
                border: 0px;
            }

            table td.no-left-border {
                border-left: 0px;
            }

            table td.no-right-border {
                border-right: 0px;
            }

            .mainTable {
                margin: 0 20px;
            }

            /* 可以在这里添加更多自定义的打印样式 */
          </style>
        </head>
        <body>
    `)

      // 将 .qrCodeContainer 的内容复制到打印窗口的 body 中
      const cloneContainer = qrCodeContainer.cloneNode(true)
      printWindow!.document.body.appendChild(cloneContainer)

      printWindow!.document.write(`
        </body>
      </html>
    `)
      printWindow!.document.close()

      // 开始打印
      printWindow!.print()

      // 打印完成后，可以恢复 .qrCodeContainer 的原始显示状态
      qrCodeContainer.style.display = 'none'
    }
  }, 600)
}

const getBrandList = async () => {
  const res = (await LoginWork.post(`/subcontract/config/combo`)) as any
  formList.value[9].selectOptions = res.data.map((item: any) => ({
    optionLabel: item.brandShortName,
    optionValue: item.brandShortName
  }))
}
onMounted(() => {
  getBrandList()
})
</script>

<style lang="less" scoped>
// .printContent2 {
//   display: none;
// }

:deep(.el-table__body tr.current-row > td) {
  color: black;
}

:deep(.el-table__row tr.current-row > td) {
  background-color: #ffe080 !important;
  color: black;
}

:deep(.el-table .el-table__cell) {
  padding: 0;
}

:deep(.el-table__body tr:first-child) {
  background-color: white;
  color: black;
}

.JSelect {
  width: 150px;
}

/* 打印 */
.pad3 {
  padding: 3px;
}

.main {
  display: flex;
  justify-content: center;
}

.left {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.headerTable {
  height: auto;
  border: 0px solid #000;
  text-align: center;
  display: flex;
  margin: 20px 20px 0px;
  vertical-align: top;
}

.title {
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.center {
  text-align: center;
}

.right {
  text-align: right;
}

.left {
  text-align: left;
}

.no-padding {
  padding: 0;
}

.no-margin {
  margin: 0;
}

.margin-5 {
  margin: 5px;
}

.margin-top-5 {
  margin-top: 5px;
}

.margin-top-15 {
  margin-top: 15px;
}

.size-8 {
  font-size: 8px !important;
}

.size-10 {
  font-size: 10px;
}

.size-12 {
  font-size: 12px;
}

.size-14 {
  font-size: 14px;
}

.size-16 {
  font-size: 17px;
}

.size-18 {
  font-size: 18px;
}

.size-24 {
  font-size: 24px;
}

#date-tip {
  position: relative;
}

span.tip {
  display: inline-block;
  height: 14px;
  line-height: 14px;
  margin-right: 30px;
}

table {
  font-size: 10px;
  border-collapse: collapse;
  border-spacing: 0;
  border-collapse: collapse;
  border-spacing: 0;
  empty-cells: show;
  width: 100%;
}

table th,
table td {
  border: 1px solid #000;
  font-size: 12px;
}

table.no-border,
table.no-border th,
table.no-border td {
  border: 0px;
}

table td.no-left-border {
  border-left: 0px;
}

table td.no-right-border {
  border-right: 0px;
}

.mainTable {
  margin: 0 20px;
}
.select {
  width: 780px;
}

.flex2 {
  display: flex;
  flex-direction: column;
  justify-content: space-evenly;
  align-items: center;
}
</style>
